﻿using System;
using System.Windows;
using System.Threading;
using MFW = MslDiary.Framework;
using MslDiary.Utils;

namespace MslDiary
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        private bool startupFlag;
        private Mutex mutex;//单实例运行代码
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            this.mutex = new Mutex(true, MFW.Gloable.ApplicationName, out startupFlag);
            if (!this.startupFlag)
            {
                if (!MFW.Gloable.IsMainWinShow)
                {
                    MFW.Gloable.IsMainWinShow = true;
                    //如何激活已运行实例
                }
                MessageBox.Show("程序已经启动！");
                Environment.Exit(0);
                return;
            }
            OnInit();
            Application.Current.ShutdownMode = System.Windows.ShutdownMode.OnExplicitShutdown;
            bool? dialogResult = new View.Login().ShowDialog();
            if (MFW.Gloable.LoginSuccessed && dialogResult.HasValue)
            {
                Application.Current.ShutdownMode = ShutdownMode.OnMainWindowClose;
            }
            else
            {
                Environment.Exit(0);
            }
        }
        /// <summary>
        /// 初始化
        /// </summary>
        private void OnInit()
        {
            MFW.Gloable.LoginSuccessed = false;
            MFW.Gloable.StartPath = System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
            MSL.Tool.Data.DbHelper.DatabaseType = MSL.Tool.Data.DataBaseType.SQLite;//数据库采用 SQLite
        }
        /// <summary>
        /// 系统关机前调用
        /// </summary>
        /// <param name="e"></param>
        protected override void OnSessionEnding(SessionEndingCancelEventArgs e)
        {
            base.OnSessionEnding(e);
        }
        /// <summary>
        /// 应用程序关闭前调用
        /// </summary>
        /// <param name="e"></param>
        protected override void OnExit(ExitEventArgs e)
        {
            base.OnExit(e);
            GC.Collect();
            Helper.Instance.ClearCachFile();//删除缓存文件
        }
        /// <summary>
        /// 处理应用程序未处理的异常
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            //MessageBox.Show("异常信息为：" + e.Exception.Message, "Exception", MessageBoxButton.OK);
            Helper.Instance.AlertError("异常信息为：" + e.Exception.Message + "");
            e.Handled = true;
        }
    }
}
